package com.example.blog.service.impl;

import com.example.blog.dto.SystemSettingDTO;
import com.example.blog.entity.SystemSetting;
import com.example.blog.exception.ResourceNotFoundException;
import com.example.blog.repository.SystemSettingRepository;
import com.example.blog.service.SystemSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SystemSettingServiceImpl implements SystemSettingService {
    @Autowired
    private SystemSettingRepository systemSettingRepository;

    @Override
    @Transactional
    public SystemSettingDTO createSetting(SystemSettingDTO settingDTO) {
        if (systemSettingRepository.existsBySettingKey(settingDTO.getSettingKey())) {
            throw new RuntimeException("Setting key already exists: " + settingDTO.getSettingKey());
        }

        SystemSetting setting = new SystemSetting();
        updateSettingFromDTO(setting, settingDTO);
        return convertToDTO(systemSettingRepository.save(setting));
    }

    @Override
    @Transactional
    public SystemSettingDTO updateSetting(String key, SystemSettingDTO settingDTO) {
        SystemSetting setting = systemSettingRepository.findBySettingKey(key)
                .orElseThrow(() -> new ResourceNotFoundException("Setting", "key", key));

        updateSettingFromDTO(setting, settingDTO);
        return convertToDTO(systemSettingRepository.save(setting));
    }

    @Override
    @Transactional
    public void deleteSetting(String key) {
        SystemSetting setting = systemSettingRepository.findBySettingKey(key)
                .orElseThrow(() -> new ResourceNotFoundException("Setting", "key", key));

        systemSettingRepository.delete(setting);
    }

    @Override
    public SystemSettingDTO getSettingByKey(String key) {
        return systemSettingRepository.findBySettingKey(key)
                .map(this::convertToDTO)
                .orElseThrow(() -> new ResourceNotFoundException("Setting", "key", key));
    }

    @Override
    public List<SystemSettingDTO> getPublicSettings() {
        return systemSettingRepository.findByIsPublicTrue()
                .stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public Page<SystemSettingDTO> getSettingsByCategory(String category, Pageable pageable) {
        return systemSettingRepository.findByCategory(category, pageable)
                .map(this::convertToDTO);
    }

    @Override
    public Page<SystemSettingDTO> getAllSettings(Pageable pageable) {
        return systemSettingRepository.findAll(pageable)
                .map(this::convertToDTO);
    }

    @Override
    public Map<String, String> getPublicSettingsMap() {
        return systemSettingRepository.findByIsPublicTrue()
                .stream()
                .collect(Collectors.toMap(
                        SystemSetting::getSettingKey,
                        SystemSetting::getSettingValue
                ));
    }

    @Override
    @Transactional
    public void initializeDefaultSettings() {
        Map<String, SystemSettingDTO> defaultSettings = new HashMap<>();
        
        // 网站基本设置
        defaultSettings.put("site.name", createDefaultSetting("site.name", "我的博客", "网站名称", "基本设置", true));
        defaultSettings.put("site.description", createDefaultSetting("site.description", "一个优雅的博客系统", "网站描述", "基本设置", true));
        defaultSettings.put("site.keywords", createDefaultSetting("site.keywords", "博客,Java,Spring Boot", "网站关键词", "基本设置", true));
        defaultSettings.put("site.icp", createDefaultSetting("site.icp", "", "ICP备案号", "基本设置", true));
        
        // 功能设置
        defaultSettings.put("comment.enabled", createDefaultSetting("comment.enabled", "true", "是否开启评论", "功能设置", true));
        defaultSettings.put("register.enabled", createDefaultSetting("register.enabled", "true", "是否开启注册", "功能设置", true));
        defaultSettings.put("email.notify", createDefaultSetting("email.notify", "false", "是否开启邮件通知", "功能设置", false));
        
        // 性能设置
        defaultSettings.put("cache.timeout", createDefaultSetting("cache.timeout", "3600", "缓存过期时间（秒）", "性能设置", false));
        defaultSettings.put("page.size", createDefaultSetting("page.size", "10", "默认分页大小", "性能设置", true));

        // 保存默认设置
        defaultSettings.forEach((key, setting) -> {
            if (!systemSettingRepository.existsBySettingKey(key)) {
                createSetting(setting);
            }
        });
    }

    private SystemSettingDTO createDefaultSetting(String key, String value, String description, String category, boolean isPublic) {
        SystemSettingDTO dto = new SystemSettingDTO();
        dto.setSettingKey(key);
        dto.setSettingValue(value);
        dto.setDescription(description);
        dto.setCategory(category);
        dto.setPublic(isPublic);
        return dto;
    }

    private void updateSettingFromDTO(SystemSetting setting, SystemSettingDTO dto) {
        setting.setSettingKey(dto.getSettingKey());
        setting.setSettingValue(dto.getSettingValue());
        setting.setDescription(dto.getDescription());
        setting.setCategory(dto.getCategory());
        setting.setPublic(dto.isPublic());
    }

    private SystemSettingDTO convertToDTO(SystemSetting setting) {
        SystemSettingDTO dto = new SystemSettingDTO();
        dto.setId(setting.getId());
        dto.setSettingKey(setting.getSettingKey());
        dto.setSettingValue(setting.getSettingValue());
        dto.setDescription(setting.getDescription());
        dto.setCategory(setting.getCategory());
        dto.setPublic(setting.isPublic());
        dto.setCreatedAt(setting.getCreatedAt());
        dto.setUpdatedAt(setting.getUpdatedAt());
        return dto;
    }
} 